<template>
	<section>
		<!--工具条 高级查询 新增数据-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
        <el-button type="danger" @click="batchRemove" :disabled="this.handleSelectValue.length===0">批量删除</el-button>
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表 编辑 删除-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="handleSelectionChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="产品名称" width="150" sortable>
			</el-table-column>
			<el-table-column prop="price" label="产品价格" width="150" sortable>
			</el-table-column>
			<el-table-column prop="productType.name" label="产品类型" width="150" sortable>
			</el-table-column>
			<el-table-column prop="description" label="产品描述" width="150" sortable>
			</el-table-column>
			<el-table-column prop="resource" label="产品资源" width="150" sortable>
			</el-table-column>

			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
    </el-table>
		<!--工具条 批量删除 分页查询-->
		<el-col :span="24" class="toolbar">

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
		</el-col>
		<!--新增和修改模态框界面-->
		<el-dialog title="新增/修改" :visible.sync ="productFormVisible" :close-on-click-modal="false">
			<el-form :model="productForm" label-width="80px" :rules="addFormRules" ref="productForm">
				<el-form-item label="产品名称" prop="name">
					<el-input v-model="productForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="产品价格" prop="price">
					<el-input v-model="productForm.price" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="产品类型" >
<!--					<el-input v-model="productForm.manager.id" auto-complete="off"></el-input>-->
          <el-select v-model="productForm.productType" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in types"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.description }}</span>
            </el-option>
          </el-select>
				</el-form-item>
				<el-form-item label="产品描述">
					<el-input type="textarea" v-model="productForm.description"></el-input>
				</el-form-item>
				<el-form-item label="产品资源">
					<el-input type="textarea" v-model="productForm.resource"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="productFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
			  types:[],//用来接收所有的产品类型做类型选择下拉框
				query: {
					currentPage: 1,
          pageSize: 10,
          keyword: ""
				},
				pageInfo: {
				  total: 0,//分页查询总条数
          rows: []//当前页展示数据
        },

				listLoading: false,//渲染列表页面时加载等待
        saveLoading: false,//保存页面时加载等待
				handleSelectValue: [],//里面装的是列表选中行的数据
				editFormRules: {
					name: [
						{ required: true, message: '请输入产品名称', trigger: 'blur' }
					]
				},
				productFormVisible: false,//新增/修改界面是否显示,模态框是否展示
				addFormRules: {
					name: [
						{ required: true, message: '请输入产品名称', trigger: 'blur' }
					]
				},
				//新增/修改界面数据
				productForm: {
				  id: null,
					name: '',
					price: null,
          productType: {
					  id: null,
            name: ''
          },
					description: '',
          resource: ''
				}

			}
		},
		methods: {
		  //查询所有类型:做类型选择的下拉框
      getTypes(){
        this.$http.get("/productType")
            .then(result => {
              result=result.data;
              if (result.success){
                this.types=result.result;
              }else {
                this.$message({
                  message: '获取类型数据失败'+result.message,
                  type: 'error'
                });
              }
            }).catch(result =>{
          this.$message({
            message: '获取类型数据失败',
            type: 'error'
          });
        })
      },

		  //高级查询，当输入关键字搜索时调用这个方法
      search(){
        this.query.currentPage=1;
        this.getProducts();
      },
      //当当前页改变时,来重新查取数据
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getProducts();
			},
      //当当前页展示数据条数改变时，来重新查取数据
      handleSizeChange(val){
        //这里面带的参数就是当前页展示数据的条数
        this.query.pageSize=val;
        this.query.currentPage=1;
        this.getProducts();
      },
			//获取部门列表数据展示在页面
			getProducts() {
        //开始加载
				this.listLoading = true;
				this.$http.post("/product",this.query)
            .then(result =>{
              //result中装的是从后端返回来的数据，是个分页高级查询返回的数据PageList{total: rows:[]}
              result = result.data;
              // console.log(result);
              if (result.success){
                this.pageInfo = result.result;
                this.listLoading = false;
              }else {
                this.$message({
                  message: '查询分页失败'+result.message,
                  type: 'error'
                });
              }
            })
            .catch(result => {
              this.$message({
                message: '查询分页失败,没有进入后端数据库',
                type: 'error'
              })
            })
			},
			//删除操作
			handleDel: function (index, row) {
        //index是选中的行的下标，row是选中行的数据，是个Object对象
        // console.log(row)
				this.$confirm('确认删除该记录吗?', '提示', {type: 'warning'})
            .then(() => {//点击确认进入这个then中
              this.listLoading = true;
              this.$http.delete("/product/"+row.id)
                  .then(result =>{//与后端成功联通进入这个then
                    result = result.data;
                    if (result.success){
                      this.$message({
                        message: '删除成功'+result.message,
                        type: 'success'
                      });
                      this.query.currentPage = 1;
                      this.getProducts();
                      this.listLoading = false;
                    }else {
                      this.$message({
                        message: '删除失败'+result.message,
                        type: 'error'
                      });
                    }

                  })
				}).catch(result => {
          this.$message({
            message: '已取消删除',
            type: 'info'
          });
				});
			},
			//点击修改操作
			handleEdit: function (index, row) {
        //点击编辑按钮,弹出模态框,并回显编辑行的数据
				this.productFormVisible = true;
				//回显数据
				this.productForm = Object.assign({}, row);
				// debugger;
        //在新增页面可能选到类型没有的情况，这样整个type就会显示：type:null
        //而不是一个对象的形式就会报错
				if (this.productForm.type == null){
				  this.productForm.type = {id: null}
        }
				//当点击修改操作时会获取所有类型来做类型的选择下拉框
				this.getTypes();
			},
			//点击新增操作
			handleAdd: function () {
        //点击新增按钮时弹出模态框
				this.productFormVisible = true;
				//初始化数据，因为是双向绑定的，避免值累积
				this.productForm = {
          id: null,
          name: '',
          price: null,
          productType: {
            id: null,
            name: ''
          },
          description: '',
          resource: ''
				};
        //当点击新增操作时会获取所有类型来做类型选择的下拉框
        this.getTypes();
			},
			//新增和修改完了之后的保存方法
			save: function () {
				this.$refs.productForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
							let para = Object.assign({}, this.productForm);
							this.$http.put("/product",para)
                  .then(result => {
                    result = result.data;
                    if (result.success){
                      this.$message({
                        message: '提交成功'+result.message,
                        type: 'success'
                      });
                      this.productFormVisible = false;//关闭模态框
                      this.query.keyword=null;
                      this.query.currentPage = 1;//从第一页开始展示
                      this.getProducts();//重新查询列表数据
                      this.saveLoading = false;//关闭加载等待
                    }else {
                      this.$message({
                        message: '提交失败'+result.message,
                        type: 'error'
                      });
                    }
                  }).catch(result =>{
                this.$message({
                  message: '前端提交失败',
                  type: 'info'
                });
              })
						});
					}
				});
			},
      handleSelectionChange: function (rows) {
        // debugger;
        //rows是自带的一个参数，是个数组，里面装的是选中行的数据
				this.handleSelectValue = rows;
			},
			//批量删除
			batchRemove: function () {
         // debugger;
        //1先获取要删除的部门的id
        var ids =[];
				ids = this.handleSelectValue.map(prod => prod.id);
        //2.给出友情提示
				this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
            .then(() => {//用户点击确认就进入这个then
            this.listLoading = true;//渲染页面加载等待
            //发送请求到后端删除数据
              this.$http.patch("/product",ids)
                  .then(result => {
                    result=result.data;
                    if (result.success){
                      this.$message({
                        message: '批量删除成功',
                        type: 'success'
                      });
                      //从第一页从新回显部门列表数据
                      this.query.currentPage=1;
                      this.getProducts();
                      this.listLoading=false//关闭加载
                    }else {
                      this.$message({
                        message: '批量删除失败'+result.message,
                        type: 'error'
                      });
                    }
                  })
				}).catch(result => {
          this.$message({
            message: '前端批量删除失败',
            type: 'error'
          });
				});
			}
		},
		mounted() {
			this.getProducts();
		}
	}
</script>
<style scoped>

</style>